package com.monster.starter.core.utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Map;

/**
 * 上下文操作
 * @author kuang
 */
@Slf4j
public class SpringContextUtils {
    private SpringContextUtils () {}
    /**
     * spring 上下文
     */
    @Getter
    private static ApplicationContext context;
    public static synchronized void setContext (ApplicationContext context) {
        if (context != null) {
            log.info("ApplicationContext对象注入成功");
            SpringContextUtils.context = context;
        }
    }
    /**
     * 上下文的名称
     */
    public static final String contextName = "context";

    /**
     * 通过class获取bean实例
     * @param clz bean class
     * @param <T> 泛型
     * @return 对象实例
     */
    public static <T> T getBean(Class<?> clz) {
        try {
            return (T) context.getBean(clz);
        } catch (Exception e) {
            log.error("通过Spring没有找到实例bean：{}", e.getMessage());
        }
        return null;
    }
    /**
     * 通过名称获取bean实例
     * @param name 实例名称
     * @param <T> 泛型
     * @return 对象实例
     */
    public static <T> T getBean(String name) {
        try {
            return (T) context.getBean(name);
        } catch (Exception e) {
            log.error("通过Spring没有找到实例bean：{}", e.getMessage());
        }
        return null;
    }
    /**
     * 通过class获取一组bean实例
     * @param clz bean class
     * @param <T> 泛型
     * @return 对象实例
     */
    public static <T> Map<String,T> getBeans(Class<?> clz) {
        try {
            return (Map<String, T>) context.getBeansOfType(clz);
        } catch (Exception e) {
            log.error("通过Spring没有找到实例bean：{}", e.getMessage());
        }
        return null;
    }
    /**
     * 得到request对象
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = RequestUtils.get();
        if (request == null) {
            request = context.getBean(HttpServletRequest.class);
        }
        if (request == null) {
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        }
        return request;
    }
    /**
     * 得到response对象
     */
    public static HttpServletResponse getResponse() {
        HttpServletResponse response = context.getBean(HttpServletResponse.class);
        if (response == null) {
            response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        }
        return response;
    }

    /**
     * 获取请求里面的ip
     * @return ip
     */
    public static String getIp () {
        return IPUtils.getIpAddr(SpringContextUtils.getRequest());
    }
}
